package java44th.group.service.wx.order;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import java44th.group.bean.common.BasePageInfo;
import java44th.group.bean.common.CommonData;
import java44th.group.bean.po.*;
import java44th.group.bean.wx.bo.order.WxOrderAndGoodsCommentBo;
import java44th.group.bean.wx.bo.order.WxOrderCommitBo;
import java44th.group.bean.wx.vo.order.*;
import java44th.group.mapper.*;
import java44th.group.utils.LocalHost;
import java44th.group.utils.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Aurhor: 帅的一批
 * @CreateAt: 2022/10/14 10:07
 * @Description:
 * @PACKAGE_NAME： java44th.group.service.wx.order
 */

@Service
@Transactional
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    MarketOrderMapper marketOrderMapper;

    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;

    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Autowired
    MarketSystemMapper marketSystemMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Override
    public CommonData getOrderListByShowType(BasePageInfo basePageInfo, Integer showType, Integer userId) {

        //用户查询订单最多
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        if (showType != null && showType != 0) {
            PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
            short orderType1 = (short) (showType * 100);
            short orderType2 = (short) (showType * 100 + 2);
            if (orderType2 > 400) {
                orderType2 = (short) (orderType2 - 1);
                criteria.andCommentsGreaterThan((short)0);
            }
            /**
             * 101.未付款
             * 201.已付款
             * 301.已发货
             * 401.已收货
             */
            criteria.andOrderStatusBetween(orderType1, orderType2);
        }
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(userId);

        //根据用户id和订单状态查询所有的订单
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(marketOrderExample);





        //创建 返回列表
        List<WxOrderListVo> wxOrderListVoArrayList = new ArrayList<>();
        for (MarketOrder marketOrder : marketOrders) {
            //通过订单id查询 商品订单表
            MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
            MarketOrderGoodsExample.Criteria criteria1 = marketOrderGoodsExample.createCriteria();
            criteria1.andOrderIdEqualTo(marketOrder.getId());
            List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);

            //goodsList字段
            List<WxOrderListVo.GoodsListDTO> goodsListDTOS = new ArrayList<>();
            //handleOptionDao字段
            WxOrderHandleOption handleOptionDTO = null;
            // 遍历商品订单表 填入goodsList字段
            for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
                String picUrl = marketOrderGood.getPicUrl();
                if (StringUtil.isEmpty(picUrl) && !picUrl.startsWith("http")) {
                    picUrl = LocalHost.localhost + picUrl;
                }
                BigDecimal goodsPriceTemp = marketOrderGood.getPrice();
                double goodsPrice = 0;
                if (goodsPriceTemp != null) {
                    goodsPrice = goodsPriceTemp.doubleValue();
                }
                WxOrderListVo.GoodsListDTO goodsListDTO = new WxOrderListVo.GoodsListDTO(
                        (int) marketOrderGood.getNumber(),
                        picUrl,
                        goodsPrice,
                        marketOrderGood.getId(),
                        marketOrderGood.getGoodsName(),
                        marketOrderGood.getSpecifications()
                );
                goodsListDTOS.add(goodsListDTO);


            }
            //拼接handleOption
            handleOptionDTO = getHandleOption(marketOrder);
            //防止价格为空 出现空指针异常
            BigDecimal actualPriceTemp = marketOrder.getActualPrice();
            double actualPrice = 0;
            if (actualPriceTemp != null) {
                actualPrice = actualPriceTemp.doubleValue();
            }
            Long orderSn = null;
            String orderSnTemp = marketOrder.getOrderSn();
            if (orderSnTemp != null) {
                orderSn = Long.parseLong(orderSnTemp);
            }

            //返回需要类型
            WxOrderListVo wxOrderListVo = new WxOrderListVo(
                    CommonOrderStatusText.commonOrderStatusMap.get((int) (short) marketOrder.getOrderStatus()),
                    (int) marketOrder.getAftersaleStatus(),
                    //todo 是否拼团 不知道什么玩意 全部false
                    false,
                    orderSn,
                    actualPrice,
                    goodsListDTOS,
                    marketOrder.getId(),
                    handleOptionDTO
            );
            wxOrderListVoArrayList.add(wxOrderListVo);
        }

        //反转list 应该让最后下单的最先显示
        Collections.reverse(wxOrderListVoArrayList);

        PageInfo<MarketOrder> wxOrderListVoPageInfo = new PageInfo<>(marketOrders);

        return new CommonData(
                (int) wxOrderListVoPageInfo.getTotal(),
                (int) wxOrderListVoPageInfo.getPages(),
                basePageInfo.getLimit(),
                wxOrderListVoPageInfo.getPrePage(),
                wxOrderListVoArrayList
        );
    }

    @Override
    public WxOrderDetailVo getOrderDetailById(Integer orderId) {
        MarketUser marketUser = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

        //order模板
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria orderCriteria = marketOrderExample.createCriteria();

        //orderGoods模板
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria orderGoodsCriteria = marketOrderGoodsExample.createCriteria();

        //根据userid和orderid查询订单表
        orderCriteria.andIdEqualTo(orderId);
        orderCriteria.andUserIdEqualTo(marketUser.getId());

        //根据orderid查询orderGoods表
        orderGoodsCriteria.andOrderIdEqualTo(orderId);

        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(marketOrderExample);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);

        //数据库中的order数据
        MarketOrder marketOrder = marketOrders.get(0);
        MarketOrderGoods marketOrderGood = marketOrderGoods.get(0);

        WxOrderDetailVo wxOrderDetailVo = new WxOrderDetailVo(
                null,//不知道是啥 以后再说 todo
                getOrderInfo(marketOrder),
                marketOrderGoods
//                getOrderGoodsInfo(marketOrderGood)
        );


        return wxOrderDetailVo;
    }

    @Override
    public boolean updateRefundstatus(Integer orderId, Short aftersaleStatus) {
        try {
            MarketOrder marketOrder = new MarketOrder();
            marketOrder.setId(orderId);
            if (aftersaleStatus != null) {
                marketOrder.setAftersaleStatus(aftersaleStatus);
            }
            marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateOrderstatus(Integer orderId, short orderStatus) {
        try {
            MarketOrder marketOrder = new MarketOrder();
            marketOrder.setId(orderId);
            marketOrder.setOrderStatus(orderStatus);
            marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteOrderById(Integer orderId) {
        try {
            MarketOrder marketOrder = new MarketOrder();
            marketOrder.setId(orderId);
            marketOrder.setDeleted(true);

            marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
//        MarketOrderExample marketOrderExample = new MarketOrderExample();
//        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
    }

    @Override
    public MarketOrderGoods getGoodsInfoByGidAndOidToComment(Integer orderId, Integer goodsId, Integer userId) {
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andGoodsIdEqualTo(goodsId);
        //应该对 userid确认一下 否则会出现权限问题 偷懒了 不搞了
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);
        MarketOrderGoods marketOrderGoods1 = marketOrderGoods.get(0);
        if (marketOrderGoods1.getPicUrl() != null && !marketOrderGoods1.getPicUrl().startsWith("http")) {
            marketOrderGoods1.setPicUrl(LocalHost.localhost + marketOrderGoods1.getPicUrl());
        }
        return marketOrderGoods1;
    }

    @Override
    public boolean orderAndGoodsComment(WxOrderAndGoodsCommentBo wxOrderAndGoodsCommentBo) {
        try {

            //根据商品订单id更新商品评论数量 -1
            MarketOrderGoods marketOrderGoods = marketOrderGoodsMapper.selectByPrimaryKey(wxOrderAndGoodsCommentBo.getOrderGoodsId());
            MarketOrder marketOrder1 = marketOrderMapper.selectByPrimaryKey(marketOrderGoods.getOrderId());
            MarketOrder marketOrder = new MarketOrder();
            marketOrder.setId(marketOrderGoods.getOrderId());
            marketOrder.setUpdateTime(new Date());
            short newComment = (short) (marketOrder1.getComments() - 1);
            marketOrder.setComments(newComment);
            marketOrderMapper.updateByPrimaryKeySelective(marketOrder);


            //对图片放入数据库进行处理
            if (wxOrderAndGoodsCommentBo.getHasPicture() != null && wxOrderAndGoodsCommentBo.getPicUrls().length > 0) {
                for (int i = 0; i < wxOrderAndGoodsCommentBo.getPicUrls().length; i++) {
                    wxOrderAndGoodsCommentBo.getPicUrls()[i] = wxOrderAndGoodsCommentBo.getPicUrls()[i].replaceAll(LocalHost.localhost, "");
                }
            }

            Subject subject = SecurityUtils.getSubject();
            PrincipalCollection principals = subject.getPrincipals();
            MarketUser primaryPrincipal = (MarketUser) principals.getPrimaryPrincipal();

            MarketComment marketComment = new MarketComment();
            marketComment.setStar(wxOrderAndGoodsCommentBo.getStar());
            marketComment.setContent(wxOrderAndGoodsCommentBo.getContent());
            marketComment.setHasPicture(wxOrderAndGoodsCommentBo.getHasPicture());
            marketComment.setPicUrls(wxOrderAndGoodsCommentBo.getPicUrls());
            marketComment.setValueId(wxOrderAndGoodsCommentBo.getOrderGoodsId());
            marketComment.setValueId(primaryPrincipal.getId());
            marketCommentMapper.insertSelective(marketComment);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean prepayOrderById(Integer orderId) {
        try {
            MarketOrder marketOrder = new MarketOrder();
            marketOrder.setUpdateTime(new Date());
            marketOrder.setOrderStatus((short) 201);
            marketOrder.setPayTime(new Date());
            marketOrder.setPayId(UUID.randomUUID().toString());
            marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * *  101: '未付款',
     * *  102: '用户取消',
     * *  103: '系统取消',
     * *  201: '已付款',
     * *  202: '申请退款'
     * *  203: '已退款',
     * *  301: '已发货',
     * *  401: '用户收货',
     * *  402: '系统收货'
     *
     * @return
     */

    @Override
    public WxOrderStatusCount getOrderStatusCount() {
        MarketOrderExample marketOrderExample = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = marketOrderExample.createCriteria();
        MarketUser primaryPrincipal = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        criteria.andUserIdEqualTo(primaryPrincipal.getId());
        List<MarketOrder> marketOrders = marketOrderMapper.selectByExample(marketOrderExample);


        WxOrderStatusCount wxOrderStatusCount = new WxOrderStatusCount();
        wxOrderStatusCount.setUncomment(0);
        wxOrderStatusCount.setUnpaid(0);
        wxOrderStatusCount.setUnship(0);
        wxOrderStatusCount.setUnrecv(0);
        for (MarketOrder marketOrder : marketOrders) {
            if (marketOrder.getOrderStatus() == 101) {
                wxOrderStatusCount.setUnpaid(wxOrderStatusCount.getUnpaid() + 1);
            } else if (marketOrder.getOrderStatus() == 201 || marketOrder.getOrderStatus() == 202) {
                wxOrderStatusCount.setUnship(wxOrderStatusCount.getUnship() + 1);
            } else if (marketOrder.getOrderStatus() / 100 == 3) {
                wxOrderStatusCount.setUnrecv(wxOrderStatusCount.getUnrecv() + 1);
            } else if (marketOrder.getOrderStatus() == 401 && marketOrder.getComments() >= 1) {
                wxOrderStatusCount.setUncomment(wxOrderStatusCount.getUncomment() + 1);
            }
        }
        return wxOrderStatusCount;
    }

    @Override
    public void updateCommonts(Integer orderId) {
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        MarketOrderGoodsExample marketOrderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = marketOrderGoodsExample.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(marketOrderGoodsExample);

        short comments = (short) marketOrderGoods.size();
        MarketOrder marketOrder1 = new MarketOrder();
        marketOrder1.setUpdateTime(new Date());
        marketOrder1.setId(orderId);
        marketOrder1.setComments(comments);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder1);
    }

    /**
     * 用户提交信息订单
     *
     * @param wxOrderCommitBo
     * @return
     */
    @Override
    public WxOrderCommitVo orderCommit(WxOrderCommitBo wxOrderCommitBo) {
        MarketUser user = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

        // 查询用户地址表
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(wxOrderCommitBo.getAddressId());
        String address = getUserAddressByUserId(marketAddress);
        String orderSn = getOrderSn(user);
        String payId = getPayId(user);


        //根据用户id和选中状态查出选中的所有商品信息 对选中的商品加入订单表
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andCheckedEqualTo(true);
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(user.getId());
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
        if (marketCarts.size()==0){
            throw new NullPointerException();
        }
        //查询用户是否拥有优惠券
        MarketCouponUser marketCouponUser = null;
        if (wxOrderCommitBo.getUserCouponId() > 0) {
            marketCouponUser = marketCouponUserMapper.selectByPrimaryKey(wxOrderCommitBo.getUserCouponId());
        }
        //查询优惠券
        MarketCoupon marketCoupon = null;
        if (wxOrderCommitBo.getCouponId() > 0) {
            marketCoupon = marketCouponMapper.selectByPrimaryKey(wxOrderCommitBo.getCouponId());
        }

        //对优惠价进行检查 查看是否可以使用
        //是否属于当前用户 是否是可用状态

        if (marketCouponUser != null && marketCouponUser.getUserId() != user.getId() && marketCouponUser.getStatus() == 0) {
            return null;
        }
        BigDecimal couponPrice = new BigDecimal(0);
        if (marketCoupon != null) {
            couponPrice = marketCoupon.getDiscount();
        }

        // 总费用
        BigDecimal allPrice = new BigDecimal(0);

        // integralPrice 用户积分减免
        BigDecimal integralPrice = new BigDecimal(0);
//            groupon_price 拼团价格
//            orderPrice= goods_price + freight_price - coupon_price
        BigDecimal orderPrice = new BigDecimal(0);

        //actualPrice = order_price - integral_price
        BigDecimal actualPrice = new BigDecimal(0);


        //获取运费价格 大于数据库中system表 market_express_freight_min 免运费 否则是market_express_freight_value
        BigDecimal freight = new BigDecimal(0);


        MarketOrder marketOrder = new MarketOrder(
                null,
                user.getId(),
                orderSn,
                (short) 201,
                (short) 0,
                marketAddress.getName(),
                user.getMobile(),
                address,
                wxOrderCommitBo.getMessage(),
                allPrice,// 商品费用总和
                freight,
                couponPrice,
                new BigDecimal(0),//todo 用户积分减免 不知道是什么 空着
                new BigDecimal(0),//团购优惠价格也不知道
                orderPrice,
                actualPrice,
                payId,
                new Date(),
                null,//货运又后端负责 前端这里并不给予设置为null
                null,
                null,
                null,//刚新增的 退锤子的款
                null,
                null,
                null,
                new Date(),
                (short) marketCarts.size(), //可评价商品 +
                null,
                new Date(),
                new Date(),
                false
        );
        //新建订单
        marketOrderMapper.insertSelective(marketOrder);
        Integer orderid = marketOrder.getId();
        //遍历所有商品 对商品进行选中支付 加入订单商品表
        for (MarketCart marketCart : marketCarts) {
            if (marketCart.getDeleted() == true) {//如果用户被删除 告诉对方 请勿重复提交
                throw new NullPointerException();
            }

            BigDecimal price = marketCart.getPrice();
            allPrice = allPrice.add(price);
            MarketOrderGoods marketOrderGoods = new MarketOrderGoods(
                    null,
                    orderid,
                    marketCart.getGoodsId(),
                    marketCart.getGoodsName(),
                    marketCart.getGoodsSn(),
                    marketCart.getProductId(),
                    marketCart.getNumber(),
                    marketCart.getPrice(),
                    marketCart.getSpecifications(),
                    marketCart.getPicUrl(),
                    0,
                    new Date(),
                    new Date(),
                    false
            );

            //更新商品数量 用户下单以后 商品数量减少
            boolean code = updateGoodsProductByGoodsId(marketCart.getGoodsId(), (int) marketCart.getNumber());
            if (!code) {
                throw new RuntimeException();
            }
            marketOrderGoodsMapper.insertSelective(marketOrderGoods);
            //更新购物车状态 将购物车中的信息删除
            MarketCart marketCart1 = new MarketCart();
            marketCart1.setId(marketCart.getId());
            marketCart1.setDeleted(true);
            marketCart1.setUpdateTime(new Date());
            marketCart1.setChecked(false);
            marketCartMapper.updateByPrimaryKeySelective(marketCart1);
        }
        //更新用户优惠券状态

        if (marketCouponUser != null) {
            MarketCouponUser marketCouponUser1 = new MarketCouponUser();
            marketCouponUser1.setId(marketCouponUser.getId());
            marketCouponUser1.setUsedTime(new Date());
            marketCouponUser1.setOrderId(orderid);
            marketCouponUser1.setUpdateTime(new Date());
            marketCouponUser1.setStatus((short) 0);
            marketCouponUserMapper.updateByPrimaryKeySelective(marketCouponUser1);
        }

        orderPrice = getOrderPrice(couponPrice, allPrice);
        actualPrice = orderPrice.subtract(integralPrice);

        //订单信息
        MarketOrder marketOrder1 = new MarketOrder();
        marketOrder1.setId(orderid);
        marketOrder1.setGoodsPrice(allPrice);
        marketOrder1.setActualPrice(actualPrice);
        marketOrder1.setOrderPrice(orderPrice);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder1);
        return new WxOrderCommitVo(
                orderid,
                null
        );
    }

    /**
     * 用于更新商品库存数量
     *
     * @param goodsId
     * @param goodsNum
     * @return t. 成功
     * f. 失敗 库存不足
     */
    private boolean updateGoodsProductByGoodsId(Integer goodsId, Integer goodsNum) {
        try {
            MarketGoodsProductExample marketGoodsProductExample = new MarketGoodsProductExample();
            MarketGoodsProductExample.Criteria criteria = marketGoodsProductExample.createCriteria();
            criteria.andGoodsIdEqualTo(goodsId);
            List<MarketGoodsProduct> marketGoodsProducts = marketGoodsProductMapper.selectByExample(marketGoodsProductExample);
            MarketGoodsProduct marketGoodsProduct = marketGoodsProducts.get(0);
            if (marketGoodsProduct.getNumber() < goodsNum) {
                return false;
            }
            MarketGoodsProduct marketGoodsProduct1 = new MarketGoodsProduct();
            marketGoodsProduct1.setId(marketGoodsProduct.getId());
            marketGoodsProduct1.setNumber(marketGoodsProduct.getNumber() - goodsNum);
            marketGoodsProductMapper.updateByPrimaryKeySelective(marketGoodsProduct1);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //计算订单价格
    private BigDecimal getOrderPrice(BigDecimal couponPrice, BigDecimal allPrice) {
//        int number = marketCart.getNumber();
//        double price = marketCart.getPrice().doubleValue();
//
//        double result = number * price;
        if (couponPrice != null) {
            allPrice = allPrice.subtract(couponPrice);
        }

        return allPrice;
    }

    private BigDecimal getfreight(Double actualPrice) {

        double result = 0;
        MarketSystemExample marketSystemExample = new MarketSystemExample();
        MarketSystemExample.Criteria criteria = marketSystemExample.createCriteria();
        criteria.andKeyNameEqualTo("market_express_freight_min");//免运费最小值
        MarketSystemExample marketSystemExample1 = new MarketSystemExample();
        MarketSystemExample.Criteria criteria1 = marketSystemExample1.createCriteria();
        criteria1.andKeyNameEqualTo("market_express_freight_value");//运费价格
        String marketExpressFreightMin = marketSystemMapper.selectByExample(marketSystemExample).get(0).getKeyValue();
        String marketExpressFreightValue = marketSystemMapper.selectByExample(marketSystemExample1).get(0).getKeyValue();

        double v = Double.parseDouble(marketExpressFreightMin);
        if (actualPrice < v) {
            result = Double.parseDouble(marketExpressFreightValue);
        }


        return new BigDecimal(result);
    }

    private String getPayId(MarketUser user) {
        UUID uuid = UUID.randomUUID();
        String result = uuid.toString() + user.getId();
        return result;
    }

    /**
     * 生成订单编号
     *
     * @param user
     * @return
     */
    private String getOrderSn(MarketUser user) {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("ddMMyyyyhhmmss");

        String format = simpleDateFormat.format(new Date());
        format = format.trim();
        format = format.replaceAll(":", "");
        format = format + user.getId();
        return format;
    }

    //根据地址表 拼接地址详情
    private String getUserAddressByUserId(MarketAddress marketAddress) {
        String address = "";
        address = marketAddress.getProvince() + marketAddress.getCity() + marketAddress.getCounty() + marketAddress.getAddressDetail();
        return address;
    }

    /**
     * 将数据库的数据封装到前端对应的vo中
     *
     * @param marketOrder
     * @return
     */
    private WxOrderDetailVo.OrderInfoDTO getOrderInfo(MarketOrder marketOrder) {
        int orderStatus = (int) (short) marketOrder.getOrderStatus();
        BigDecimal goodsPriceTemp = marketOrder.getGoodsPrice();
        Double goodsPrice = null;
        if (goodsPriceTemp != null) {
            goodsPrice = goodsPriceTemp.doubleValue();
        }
        BigDecimal couponPriceTemp = marketOrder.getCouponPrice();
        Double couponPrice = null;
        if (couponPriceTemp != null) {
            couponPrice = couponPriceTemp.doubleValue();
        }
        BigDecimal freightPriceTemp = marketOrder.getFreightPrice();
        Double freightPrice = null;
        if (freightPriceTemp != null) {
            freightPrice = freightPriceTemp.doubleValue();
        }
        return new WxOrderDetailVo.OrderInfoDTO(
                marketOrder.getConsignee(),
                marketOrder.getAddress(),
                marketOrder.getAddTime(),
                marketOrder.getOrderSn(),
                marketOrder.getActualPrice(),
                marketOrder.getMobile(),
                marketOrder.getMessage(),
                CommonOrderStatusText.commonOrderStatusMap.get(orderStatus),
                marketOrder.getAftersaleStatus(),
                goodsPrice,
                couponPrice,
                marketOrder.getId(),
                freightPrice,
                getHandleOption(marketOrder)
        );
    }

    //用于从订单表中封装 handleOption

    /**
     * *  101: '未付款',
     * *  102: '用户取消',
     * *  103: '系统取消',
     * *  201: '已付款',
     * *  202: '申请退款'
     * *  203: '已退款',
     * *  301: '已发货',
     * *  401: '用户收货',
     * *  402: '系统收货'
     *
     * @param marketOrder
     * @return
     */
    private WxOrderHandleOption getHandleOption(MarketOrder marketOrder) {

        //用户是否可以取消
        boolean cancel = marketOrder.getOrderStatus() == 101 ? true : false;
//                marketOrder.getPayId() == null ? false : true;
        //是否可以退款 用户付款以后可以发起退款 订单状态处于201
        boolean refund = marketOrder.getOrderStatus() == 201 ? true : false;
//                marketOrder.getRefundAmount() == null ? false : true;
        //是否存在支付id 存在代表支付
        boolean pay = marketOrder.getOrderStatus() == 101 ? true : false;

        //用户是否可以评论 订单状态处于401 已经收货的时候可以评论
        boolean comment = marketOrder.getOrderStatus() == 401 && marketOrder.getComments() > 0 ? true : false;
        //可评论商品大于0
//        comment = marketOrder.getComments() > 0 ? false : true;


        // 用户是否可以确认 订单状态处于301 代表已经发货 这时候就可以确认收货
        boolean confirme = marketOrder.getOrderStatus() == 301 ? true : false;
//                marketOrder.getConfirmTime() == null ? false : true;

        //订单售后状态 0代表可以申请 订单状态处于401
        boolean afterSaleStatus = marketOrder.getAftersaleStatus() == 0 && marketOrder.getOrderStatus() == 401 ? true : false;

        //订单是否可以删除 ,不可以 只有用户为付款的时候可以删除
        boolean deleted = marketOrder.getOrderStatus() == 101 ? true : false;

        //订单状态处于 401 完成订单时可以出现再次购买按钮
        boolean rebuy = marketOrder.getOrderStatus() == 401 ? true : false;


        return new WxOrderHandleOption(
                cancel,
                deleted,
                pay,
                comment,
                confirme,
                refund,
                rebuy,
                afterSaleStatus
        );
//        return new WxOrderHandleOption(
//                cancel,
//                deleted,
//                pay,
//                comment,
//                confirme,
//                refund,
//                false,// todo rebuy字段找不到
//                afterSaleStatus
//        );
    }

}
